const router = require('koa-router')()
// const multer = require('koa-multer')
const multer = require('@koa/multer')
const fs = require('fs')
const path = require('path')
const AipBodyAnalysisClient = require('baidu-api-nodejs-sdk').bodyanalysis

router.prefix('/upload')

const storage = multer.diskStorage({
  /**
   * 设置文件的存储位置
   * @param req
   * @param file
   * @param cb
   */
  destination: function (req, file, cb) {
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const dir = './public/uploads/' + year + month + day

    // 判断目录是否存在
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, {recursive: true})
    }
    cb(null, dir)
  },
  /**
   * 设置文件名称
   * @param req
   * @param file
   * @param cb
   */
  filename: function (req, file, cb) {
    const fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname)
    cb(null, fileName)
  }
})
const upload = multer({
  storage
})

/**
 * 上传图片
 */
router.post('/img', upload.single('myfile'), async ctx => {
  const filePath = ctx.request.file.path
  const fileWebPath = ctx.origin + '' + filePath.replace('public', '')
  ctx.body = {
    data: fileWebPath
  }
})

/**
 * 富文本编辑器上传图片
 */
router.post('/editor/img', upload.single('editorFile'), async ctx => {
  const filePath = ctx.request.file.path
  const fileWebPath = ctx.origin + '' + filePath.replace('public', '')
  ctx.body = {
    errno: 0,
    data: [{
      url: fileWebPath,
      alt: '',
      href: ''
    }]
  }
})

/**
 * 上传图片
 */
router.post('/baidu/img', upload.single('baidu'), async ctx => {
  const filePath = ctx.request.file.path
  const image = fs.readFileSync(filePath).toString('base64')
  const APP_ID = '25127363'
  const API_KEY = '3A5Tx3ZwcIVysWzGS0W6Wha2'
  const SECRET_KEY = '0CLW3tQNPtVzvfrUrGDHf4AUh67KiTx0'
  const client = new AipBodyAnalysisClient(APP_ID, API_KEY, SECRET_KEY)
  try {
    await client
      .bodySeg(image, {
        type: 'foreground'
      })
      .then((result) => {
        ctx.body = {
          code: 200,
          data: {
            extName: path.extname(filePath),
            result: JSON.stringify(result)
          }
        }
        console.log('filePath then')
      })
      .catch((err) => {
        console.log('filePath OK catch')
        // 如果发生网络错误
        ctx.body = {
          code: 300,
          data: err
        }
      })
  } catch (err) {
    ctx.body = {
      code: 500,
      data: err
    }
    console.log('filePath ERR')
  }
})
// router.post('/img', upload.single('baiduapi'), async ctx => {
//   const filePath = ctx.request.file.path
//   const fileWebPath = ctx.origin + '' + filePath.replace('public', '')
//   ctx.body = {
//     data: fileWebPath
//   }
// const APP_ID = '25127363'
// const API_KEY = '3A5Tx3ZwcIVysWzGS0W6Wha2'
// const SECRET_KEY = '0CLW3tQNPtVzvfrUrGDHf4AUh67KiTx0'
// const client = new AipBodyAnalysisClient(APP_ID, API_KEY, SECRET_KEY)
// const filePath = ctx.request.file.path
// console.log('filePath', filePath)
// ctx.body = {
//   data: fileWebPath
// }
// const fileWebPath = ctx.origin + '' + filePath.replace('public', '')
// try {
//   const image = fs.readFileSync(filePath).toString('base64');
//   client
//     .bodySeg(image)
//     .then((result) => {
//       ctx.body = {
//         code: 200,
//         data: JSON.stringify(result)
//       }
//     })
//     .catch((err) => {
//       // 如果发生网络错误
//       ctx.body = {
//         code: 300,
//         data: err
//       }
//     })
// } catch (err) {
//   ctx.body = {
//     code: 500,
//     data: err
//   }
// }
// })

module.exports = router
